<template>
    <div class="search-content" :class="{ 'row-activity': (position == 'left' || position == 'right') }">
        <header v-if="popupVm.title">
            <span>{{ popupVm.title }}</span>
            <van-icon name="cross" @click.native.stop="close()" />
        </header>

        <ul>
            <template v-for="(item, index) in handleSearchData">
                <!-- 输入框 -->
                <template v-if="item.type == 'input'">
                    <li :key="index" class="v-input-li">
                        <h4>{{ item.label }}</h4>
                        <van-field v-model="item.value" :placeholder="item.placeholder" clearable />
                    </li>
                </template>
                <!-- 输入框 end -->

                <!-- 输入框2 -->
                <template v-if="item.type == 'input2'">
                    <li :key="index" class="v-input-li">
                        <van-search v-model="item.value" :placeholder="item.placeholder"
                            :left-icon="require('@/assets/img/search.svg')" />
                    </li>
                </template>
                <!-- 输入框 end -->

                <!-- 单选 -->
                <template v-if="item.type == 'radio'">
                    <li :key="index" class="v-radio-li">
                        <h4>{{ item.label }}</h4>
                        <div class="v-radio-content">
                            <template v-for="(arrItem, arrIndex) in item._columns.arr">
                                <span class="select-item" :class="{ 'active': arrItem[item._columns.code] === item.value }"
                                    @click.stop="handleRadio(item, arrItem)" :key="arrIndex">{{ arrItem[item._columns.name]
                                    }}</span>
                            </template>
                        </div>
                    </li>
                </template>
                <!-- 单选 end -->

                <!-- 多选 -->
                <template v-if="item.type == 'checkbox'">
                    <li :key="index" class="v-checkbox-li">
                        <h4>{{ item.label }}</h4>
                        <div class="v-checkbox-content">
                            <template v-for="(arrItem, arrIndex) in item._columns.arr">
                                <span class="select-item"
                                    :class="{ 'active': item.value.some(code => code === arrItem[item._columns.code]) }"
                                    @click.stop="handleCheckbox(item, arrItem)" :key="arrIndex">{{
                                        arrItem[item._columns.name] }}</span>
                            </template>
                        </div>
                    </li>
                </template>
                <!-- 多选 end -->

                <!-- 日期 -->
                <template v-if="item.type == 'date' || item.type == 'date-range' || item.type == 'date-multiple'">
                    <li :key="index" class="v-date-li">
                        <h4>{{ item.label }}</h4>
                        <van-field v-model="item.value" :placeholder="item.placeholder" disabled clearable
                            clear-trigger="always" @click.stop="item.showCalendar = true"
                            @clear="calendarClear($event, item)" />
                        <v-calendar :ref="item.vantId" v-model="item.showCalendar" :min-date="minDate" :max-date="maxDate"
                            v-bind="item.vantOps" :default-date="currentDate" @confirm="calendarConfirm($event, item)" />
                    </li>
                </template>
                <!-- 日期 end -->

                <!-- 开关 -->
                <template v-if="item.type == 'switch'">
                    <li :key="index">
                        <h4>{{ item.label }}</h4>
                        <van-switch v-model="item.vantValue" v-bind="item.vantOps" @change="switchChange($event, item)" />
                    </li>
                </template>
                <!-- 开关 end -->
            </template>
        </ul>

        <footer>
            <div class="btn-box">
                <van-row gutter="12">
                    <van-col span="8">
                        <van-button round :text="parentVm.resetText" class="reset" @click="handleReset()" />
                    </van-col>
                    <van-col span="16">
                        <van-button round :text="parentVm.searchText" @click="handleSubmit()" />
                    </van-col>
                </van-row>
            </div>
            <!-- <div @click="handleReset()">
                <van-icon name="brush-o" />
                <span>{{ parentVm.resetText }}</span>
            </div>
            <span @click="handleSubmit()">{{ parentVm.searchText }}</span> -->
        </footer>
    </div>
</template>

<script>
import vCalendar from '../../vant/v-calendar.vue'

export default {
    inject: ["popupVm"],
    props: {
        // 弹出的方向 本来是不需要这个的 但现在从上、下、左、右弹出的都用这个组件的加上这个属性 目前主要是控制高度
        position: {
            type: String,
            default: 'bottom'
        }
    },
    components: {
        vCalendar
    },
    data () {
        return {
            // 本组件使用的控件数据
            ulData: [],
            minDate: new Date(2023, 1, 1),
            maxDate: new Date(2083, 12, 1),
            currentDate: new Date(),
        }
    },
    computed: {
        parentVm () {
            if (this.popupVm) {
                return this.popupVm
            } else {
                console.warn('bottom：没有接收到popupVm')
                return {}
            }
        },
        // 处理searchData之后的数据 主要是给默认值
        handleSearchData () {
            this.ulData=[]
            this.parentVm.searchData.map(item => {
                // 控件绑定值
                if (item.value == undefined) {
                    this.$set(item, 'value', '')
                }

                if (item.type == 'checkbox') {
                    item.value = []
                }

                // 占位符placeholder的默认值
                if (item.placeholder == undefined) {
                    if (item.type == 'date' || item.type == 'date-range' || item.type == 'date-multiple') {
                        this.$set(item, 'placeholder', '请选择')
                    } else if (item.type == 'input') {
                        this.$set(item, 'placeholder', '请输入')
                    } else if (item.type == 'input2') {
                        this.$set(item, 'placeholder', '请输入')
                    }
                }

                // 单选、多选 根据columns生成_columns
                // 还有一种方式是直接生成code、name的数组，这样组件内取值就直接code、name了
                if (item.type == 'radio' || item.type == 'checkbox') {
                    this.$set(item, '_columns', {
                        arr: [],
                        code: 'code',
                        name: 'name'
                    })

                    if (Array.isArray(item.columns)) {
                        item._columns.arr = item.columns
                    } else {
                        Object.assign(item._columns, item.columns)
                    }
                }

                // 日期
                if (item.type == 'date' || item.type == 'date-range' || item.type == 'date-multiple') {
                    // 默认配置
                    let def = {
                        formatValue: 'yyyy-MM-dd',
                        showCalendar: false,
                        join: '至',
                        vantId: item.key
                    }

                    if (Array.isArray(def.vantId)) {
                        def.vantId = def.vantId.join(',')
                    }

                    // vant组件的默认配置
                    let defVantOps = {
                        color: '#1989fa',
                        defaultDate: null,
                        type: 'single'
                    }

                    if (item.type == 'date-range') {
                        defVantOps.type = 'range'
                    }

                    if (item.type == 'date-multiple') {
                        defVantOps.type = 'multiple'
                    }

                    item.vantOps = Object.assign({}, defVantOps, item.vantOps || {})
                    item = Object.assign(def, item)
                }

                // 开关
                if (item.type == 'switch') {
                    if (item.columns == undefined) {
                        this.$set(item, 'columns', [0, 1])
                    }

                    this.$set(item, 'vantValue', false)

                    if (item.value === item.columns[1]) {
                        item.vantValue = true
                    } else {
                        item.value = item.columns[0]
                    }
                }

                this.ulData.push(item)
            })

            return this.ulData
        }
    },
    methods: {
        // 关闭组件
        close () {
            this.parentVm.visible = false
        },
        // 单选item点击
        handleRadio (item, arrItem) {
            if (item.value === arrItem[item._columns.code]) { // 当前是选中状态
                item.value = ''
            } else {
                item.value = arrItem[item._columns.code]
            }
        },
        // 多选item点击
        handleCheckbox (item, arrItem) {
            let index = item.value.findIndex(code => code === arrItem[item._columns.code])

            if (index == -1) { // 当前是未选中状态
                item.value.push(arrItem[item._columns.code])
            } else {
                item.value.splice(index, 1)
            }
        },
        // 清除日期
        calendarClear (evt, item) {
            // 重置值
            this.handleDateAssignment(true, item.vantOps.type, item)
            // 重置日期选择器
            this.resetCalendar(item.vantId)
        },
        // 日期确定
        calendarConfirm (date, item) {
            item.showCalendar = false
            if (item.vantOps.type == "range") {
                const [start, end] = date;

                item.value = `${this.$formatter.formatDate(start, item.formatValue)}${item.join}${this.$formatter.formatDate(end, item.formatValue)}`
            } else if (item.vantOps.type == 'multiple') {
                let value = ''

                value = date.reduce((val, dateItem, index) => {
                    if (index === 0) {
                        return this.$formatter.formatDate(dateItem, item.formatValue)
                    } else {
                        return `${val}${item.join}${this.$formatter.formatDate(dateItem, item.formatValue)}`
                    }
                }, value)

                item.value = value
            } else {
                item.value = this.$formatter.formatDate(date, item.formatValue)
            }
        },
        // 重置日历
        resetCalendar (vantId) {
            let vm = this.$refs[vantId][0]

            vm && vm.reset()
        },
        // 开关切换
        switchChange (val, item) {
            item.vantValue = val

            if (val === true) {
                item.value = item.columns[1]
            } else {
                item.value = item.columns[0]
            }
        },
        // 重置
        handleReset () {
            this.ulData.map(item => {
                if (item.type == 'input' || item.type == 'radio' || item.type == 'input2') {
                    item.value = ''
                }

                if (item.type == 'checkbox') {
                    item.value = []
                }

                if (item.type == 'date' || item.type == 'date-range' || item.type == 'date-multiple') {
                    this.handleDateAssignment(true, item.vantOps.type, item)
                }

                if (item.type == 'switch') {
                    item.value = item.columns[0]
                }
            })

            let obj = this.createParams()

            this.parentVm.$emit('btn:click', {
                type: 'reset',
                data: obj
            })
            this.parentVm.autoClose && this.close()
        },
        // 提交
        handleSubmit () {
            let obj = this.createParams()

            this.parentVm.$emit('btn:click', {
                type: 'search',
                data: obj
            })
            this.parentVm.autoClose && this.close()
        },
        // 创建搜索obj
        createParams () {
            let obj = {}

            this.ulData.map(item => {
                // 输入框、单选
                if (item.type == 'input' || item.type == 'radio' || item.type == 'switch' || item.type == 'input2') {
                    obj[item.key] = item.value
                }

                // 多选
                if (item.type == 'checkbox') {
                    // 后端不接受array   需要用,号拼接
                    obj[item.key] = item.value.join(',')
                }

                // 日期
                if (item.type == 'date' || item.type == 'date-range' || item.type == 'date-multiple') {
                    this.handleDateAssignment(false, item.vantOps.type, item, obj)
                }
            })

            return obj
        },
        // 处理日期的赋值
        handleDateAssignment (isReset, type, item, obj) {
            if (isReset) { // 重置
                if (type == 'range') { // 选择区间
                    if (Array.isArray(item.key)) {
                        item.key = []
                        item.value = ''
                    } else {
                        item.value = ''
                    }
                } else {
                    item.value = ''
                }

                // 重置日期选择器
                this.resetCalendar(item.vantId)
            } else { // 提交
                if (type == 'range') { // 选择区间
                    if (Array.isArray(item.key)) { // 后端需要两个字段
                        const [start, end] = item.value.split(item.join)

                        obj[item.key[0]] = start
                        obj[item.key[1]] = end
                    } else { // 后端需要一个字段 用,拼接
                        obj[item.key] = item.value.split(item.join).join(',')
                    }
                } else if (type == 'multiple') { // 多个日期
                    obj[item.key] = item.value.split(item.join).join(',')
                } else {
                    obj[item.key] = item.value
                }
            }
        }
    }
}
</script>

<style lang="less" scoped>
@deep: ~">>>";

@defBack: #f5f7fa;
@activeBack: rgba(51, 133, 255, 0.08);

.search-content {
    min-height: 40vh;
    max-height: 80vh;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    &.row-activity {
        height: 100vh;
        max-height: 100vh;
    }

    >header {
        flex-shrink: 0;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 20px 60px;
        position: relative;
        font-size: 16px;
        font-weight: 600;
        color: #333333;
        line-height: 23px;

        .van-icon {
            position: absolute;
            top: 0;
            bottom: 0;
            right: 26px;
            margin: auto;
            width: 15px;
            height: 15px;
            color: #61677a;
        }
    }

    >footer {

        // 按钮
        .btn-box {
            flex: 0 0 auto;
            padding: 15px;

            .van-button {
                height: 48px;
                font-size: 18px;
                font-weight: 400;
                color: #fff;
                background-color: #1990FF;
                border: none;

                &.reset {
                    color: #1990FF;
                    background-color: rgba(59, 127, 250, 0.14);
                    border: none;
                }
            }
        }
    }

    span.select-item {
        font-size: 14px;
        font-weight: 400;
        color: #333;
        line-height: 20px;
        background: @defBack;
        border-radius: 4px;
        padding: 8px 15px;
        margin: 0 10px 12px 0;

        &.active {
            background: @activeBack;
            color: #1990FF;
        }
    }

    ul {
        flex: 1;
        overflow-y: auto;
        margin: 0;
        padding: 0 20px 20px;

        li {
            display: flex;
            flex-direction: column;

            &+li {
                margin-top: 10px;
            }

            >h4 {
                font-size: 16px;
                font-weight: 600;
                color: #333333;
                line-height: 23px;
                padding: 8px 0 15px;
                margin: 0;
            }

            .v-radio-content,
            .v-checkbox-content {
                display: flex;
                flex-wrap: wrap;
            }

            &.v-input-li {
                .van-field {
                    background: @defBack;
                    border-radius: 44px;
                }

                @{deep}.van-search {
                    padding: 0;

                    .van-search__content {
                        border-radius: 35px;

                        input {
                            &::placeholder {
                                font-size: 14px;
                                color: #61677a;
                                line-height: 20px;
                            }
                        }
                    }

                    .van-icon__image {
                        width: 15px;
                        height: 15px;
                        padding-top: 4px;
                    }
                }
            }

            &.v-date-li {
                .van-field {
                    background: @defBack;
                    border-radius: 4px;
                }
            }
        }
    }
}
/deep/ .van-field__control:disabled{
    color: #323233;
    -webkit-text-fill-color: #323233;
}
</style>
